<?php

namespace App\Services;

use App\Models\GoodsSpecs;
use App\Models\GoodsSpecsValue;

class GoodsSpecsService extends BaseService
{
    /**
     * 获取规格列表
     * @return
     */
    public function list($page,$limit,$name) {
        $query = GoodsSpecs::query();
        if(isset($name)){
            $query->where('name','like',"%$name%");
        }
        return $query->paginate($limit, ['*'], 'page', $page);
    }
    /**
     * 获取全部规格列表
     * @return
     */
    public function listAll($name) {
        $query = GoodsSpecs::query();
        if(isset($name)){
            $query->where('name','like',"%$name%");
        }
        return $query->get();
    }
    /**
     * 根据规格id获取规格值列表
     * @return
     */
    public function specsVallist($goods_specs_id) {
        $query = GoodsSpecsValue::query();
        if(isset($goods_specs_id)){
            $query->where('goods_specs_id',$goods_specs_id);
        }
        return $query->get();
    }
    /**
     * 规格值拼接规格名称
     * @return
     */
    public function getNormalInIds($ids) {
        if(!$ids){
            return [];
        }
        $result = GoodsSpecsValue::whereIn('id',$ids)->get();
        $result = $result->toArray();
        if(!$result){
            return [];
        }
        $specsName = GoodsSpecs::get()->toArray();
        $specsNameArr = array_column($specsName,'name','id');
        $res = [];
        foreach ($result as $v){
            $res[$v['id']]=[
                'name' => $v['name'],
                'specsName' => $specsNameArr[$v['goods_specs_id']] ?? ''
                ];
        }
        return $res;
    }
    public function dealSpecsVal($skuIdSpecsValIds) {
        $ids = array_values($skuIdSpecsValIds);
        $ids = implode(',',$ids);
        $ids = array_unique(explode(',',$ids));
        $result = $this->getNormalInIds($ids);
        if(!$result){
            return [];
        }
        $res = [];
        foreach ($skuIdSpecsValIds as $skuId => $specs){
            $specs = explode(',',$specs);
            $skuStr = [];
            foreach ($specs as $spec){
                $skuStr[]=$result[$spec]['specsName'].":".$result[$spec]['name'];
            }
            $res[$skuId] = implode("  ",$skuStr);
        }
       return $res;
    }
}
